import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author quan
 * @Description 添加数据
 * @Date 2023/6/29 11:12
 */

@WebServlet("/addmsg")
public class addMessageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、设置编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        //2、获取表白数据：三个属性
        String username = req.getParameter("username");
        String touser = req.getParameter("touser");
        String msg = req.getParameter("msg");
        //3、判空
        HashMap<String,Object> map = new HashMap<String, Object>();
        //数据有问题
        if(username == null || username.equals("")||
            touser == null || touser.equals("") ||
                msg == null || msg.equals("")
        ){
            //设置返回数据类型格式：3个
            map.put("code",-1);
            map.put("msg","非法参数");
            map.put("data","");
        }else{
            //数据正常,将属性设置到message对象中
            Message message = new Message();
            message.setUsername(username);
            message.setToUser(touser);
            message.setMsg(msg);
            //将message对象存储到集合中
            AppVar.MESSAGE_LIST.add(message);
            //设置返回数据格式：3个
            map.put("code",200);
            map.put("msg","");
            map.put("data",1);
        }
        //4、返回数据
        String jsonStr = AppVar.OBJECT_MAPPER.writeValueAsString(map);
        resp.getWriter().write(jsonStr);
    }
}
